package com.biz.user.delayQueue;

import com.alibaba.fastjson.*;
import com.biz.redis.util.*;
import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;
import org.springframework.util.*;

import javax.annotation.*;
import java.util.*;
import java.util.stream.*;

/**
 * @Description
 *    发布任务
 * @Author liuxi
 * @Date 2024/5/10
 **/
@Slf4j
@Service
public class MassMailTaskService {

    @Resource
    private RedisUtil redisUtil;

    private static final String MASS_TASK_KEY = "massMailTask";


    /**
     * 发布任务
     *
     * @param massMailTask 任务
     */
    public void pushMassMailTaskQueue(MassMailTask massMailTask) {
        Date startTime = massMailTask.getStartTime();
        if (startTime == null) {
            return;
        }
        if (startTime.compareTo(new Date()) <= 0) {
            return;
        }
        log.info("定时群发任务加入延时队列，massMailTask:{}", JSON.toJSON(massMailTask));
        redisUtil.zAdd(MASS_TASK_KEY, massMailTask.getTaskId().toString(), startTime.getTime());
    }

    /**
     * 拉起任务
     *
     */
    public Set<Long> poolMassTaskQueue() {
        Set<String> taskIdSet = redisUtil.rangeByScore(MASS_TASK_KEY, 0, System.currentTimeMillis());
        if (CollectionUtils.isEmpty(taskIdSet)) {
            return Collections.emptySet();
        }
        redisUtil.removeZsetList(MASS_TASK_KEY, taskIdSet);
        return taskIdSet.stream().map(Long::parseLong).collect(Collectors.toSet());
    }
}
